<?php

class CoreExperiment
{

    use CoreTraitTimer;

    protected bool $debug = false;
    protected int $memory = 0;

    /**
     * @param bool $debug
     */
    public function __construct(bool $debug = false)
    {
        $this->debug = $debug;
        $this->memory = memory_get_usage();
        $this->begin();
    }

    public function __destruct()
    {
        if ($this->debug) {
            $this->record();
            $memory = readableBytes(memory_get_usage() - $this->memory);
            $exec = $this->exec();
            print_r(compact('exec', 'memory'));
        }
    }


    public static function exclusive()
    {

    }

    public function efficiency($function, $param_arr = [], $times = 1): void
    {
        $m = memory_get_usage();

        $this->begin();

        while (true) {
            //执行目标函数
            call_user_func_array($function, $param_arr);

            $this->record();

            if ($this->getTimes() >= $times) break;
        }

        echo 'times:', $this->getTimes(), ' total:', $this->end() ,' average:', $this->average(), ' max:', $this->max(), PHP_EOL;
        echo 'm start:', readableBytes($m) , PHP_EOL;
        echo 'm diff:', readableBytes(memory_get_usage() - $m) , PHP_EOL;
    }

    public static function limitation($page_size)
    {
        $p = 1;
        $scrollId = '';
        $ids = [];
        while (true) {
            $offset = $p >= 1  ? ($p - 1) * $page_size : 0;
            $minimax = $offset + $page_size;
            $where["LIMIT"] = [$offset, $page_size];

            $rs = ['total' => 91, 'rows' => [ ['uid' => rand(100000, 90000000)]], 'scroll_id' => 'hello'];
            $total = $rs['total'] ?? 0;
            $scrollId = $rs['scroll_id'] ?? '';
            $rows = $rs['rows'] ?? [];
            $rows = empty($rows) ? [] : array_column($rows, 'uid');
            $ids = array_merge($ids, $rows);

            //结束条件判断
            if ($total <= $minimax) {
                echo 'end ' , $scrollId , PHP_EOL;
                break;
            }
            $p ++;
        }
    }
}